<template>
  <q-field
    outlined
    dense
    ref="field"
    :readonly="readonly"
    :rules="required?[requiredTest]:undefined"
  >
    <template #control class="row">
      <div>{{range&&range.from}}</div>
      <div class="col text-center">至</div>
      <div>{{range&&range.to}}</div>
    </template>
    <template #append>
      <q-icon name="date_range" color="primary"/>
    </template>
    <q-menu>
      <div  class="q-gutter-xs row items-start">
        <q-date minimal v-model="range.from" @input="changeStartDate" mask="YYYY-MM-DD" />
        <q-date minimal v-model="range.to" :options="optionsFn" @input="changeDate" mask="YYYY-MM-DD" />
      </div>
    </q-menu>
  </q-field>
</template>

<script>
import { requiredTest } from 'boot/inputTest';
import { replaceAll } from 'boot/util';

export default {
  components: {
  },
  props: {
    required: Boolean,
    readonly: Boolean,
    formData: {
      type: Object,
    },
    formKey: {
      type: String,
    },
  },
  data() {
    return {
      range: {
        from: '',
        to: '',
      },
    };
  },
  methods: {
    requiredTest,
    validate() {
      return this.$refs.field.validate();
    },
    resetValidation() {
      return this.$refs.field.resetValidation();
    },
    changeDate() {
      this.formData[this.formKey] = this.range;
    },
    changeStartDate() {
      if (!this.range.to || this.range.from > this.range.to) {
        this.range.to = this.range.from;
      }
      this.changeDate();
    },
    optionsFn(date) {
      if (!this.range) {
        return false;
      }
      if (!this.range.from && !this.range.to) {
        return true;
      }
      if (!this.range.from) {
        this.range.from = this.range.to;
      }
      const d = replaceAll(date, '/', '-');
      return d >= this.range.from;
    },
  },
  created() { },
  mounted() {
    if (this.formData[this.formKey]) { this.range = this.formData[this.formKey]; }
  },
  watch: {
    formData: {
      handler() {
        if (this.formData[this.formKey]) {
          this.range = this.formData[this.formKey];
        } else {
          this.range.from = '';
          this.range.to = '';
        }
      },
      deep: true,
    },
  },
  computed: {},
};
</script>
<style lang="stylus"></style>
